<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 签到类
 * @package  module/base/promotion
 * @subpackage
 * @author   allen.qiang
 * @version 1.0
 */

class signIn {

    private $dbca;

    public function __construct( &$dbca ) {
        $this->dbca = $dbca;
    }

    /**
     * 查询签到活动
     * @param $arg_array
     * @return array|null
     */
    public function searchSigneToList(&$arg_array){

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //签到活动ID
        if (isset($arg_array['promotionID']) && is_numeric($arg_array['promotionID'])) {
            $sql .= ' AND promotionID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['promotionID'];
        }

        //签到活动主题
        if (isset($arg_array['promotionName']) && !empty($arg_array['promotionName'])) {
            $sql .= ' AND promotionName like ?';
            $params_type .= 's';
            $params_array[] = '%'.$arg_array['promotionName'].'%';
        }

        //日期
        if (isset($arg_array['startDate']) && !empty($arg_array['startDate'])) {
            $sql .= ' AND startDate <= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['startDate'];
        }

        if (isset($arg_array['endDate']) && !empty($arg_array['endDate'])) {
            $sql .= ' AND endDate >= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['endDate'];
        }

        //使用标识
        if (isset($arg_array['useFlg']) && in_array($arg_array['useFlg'], array(0, 1))) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4) ;
        }

        try {

            if (isset($arg_array['rp'])) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM promotion_sign_in  ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询备注信息
            $search_sql = 'SELECT * FROM promotion_sign_in ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

            if (!$temp_item_array)
                return null;

            if ($temp_item_array) {
                foreach ($temp_item_array as &$item) {

                    $item_array[] = array(
                        'createTime' => $item->createTime,                //创建时间
                        'promotionID' => $item->promotionID,                //签到活动ID
                        'promotionName' => $item->promotionName,            //签到活动主题
                        'description' => $item->description,            //描述
                        'startDate' => $item->startDate,            //开始日期
                        'endDate' => $item->endDate,            //结束日期
                        'points' => $item->points,            //赠送积分
                        'continuousDay' => $item->continuousDay,            //连续签到天数
                        'extraPoints' => $item->extraPoints,            //额外赠送积分
                        'useFlg' => $item->useFlg,            //使用标志：1、是 0、否
                        'useFlgName' => $item->useFlg ? '启用' : '禁用'
                    );
                }
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 新增或修改签到活动
     * @param array $arg_array
     * @return array
     */
    public function editSignIn( $arg_array ) {

        //实例公共类
        $commHandler = new commHandler( $this->dbca );

        if (!isset($arg_array['promotionID'], $arg_array['promotionName'], $arg_array['description'], $arg_array['startDate'], $arg_array['endDate'],
        $arg_array['points'], $arg_array['continuousDay'], $arg_array['extraPoints'], $arg_array['operator'])) {
            return array( 'code'=> 400, 'message' => '参数错误' );
        }

        //活动主题
        if(empty($arg_array['promotionName'])){
            return array( 'code' => 400, 'message' => '活动名称不能为空' );
        }

        //活动时间
        if(!$commHandler->isDate($arg_array['startDate']) || !$commHandler->isDate($arg_array['endDate'])){
            return array( 'code' => 400, 'message '=> '请选择活动开始和结束日期' );
        }
        if($arg_array['endDate'] < $arg_array['startDate']){
            return array( 'code' => 400, 'message' => '开始日期不能大于结束日期' );
        }

        //赠送积分
        if (!$commHandler->isInteger($arg_array['points'], 1) && strlen($arg_array['points']) > 4) {
            return array( 'code' => 400, 'message' => '赠送积分不能为空且是大于0的4位整数' );
        }

        //连续签到天数
        if (!empty($arg_array['continuousDay'])) {
            if (!$commHandler->isInteger($arg_array['continuousDay'], 1) && strlen($arg_array['continuousDay']) > 4) {
                return array( 'code' => 400, 'message' => '连续签到天数必须是大于0的4位整数' );
            }
            if (!$commHandler->isInteger($arg_array['extraPoints'], 1) && strlen($arg_array['extraPoints']) > 4) {
                return array( 'code' => 400, 'message' => '额外赠送积分不能为空且是大于0的4位整数' );
            }
        }

        //额外赠送积分
        if (!empty($arg_array['extraPoints'])) {
            if (!$commHandler->isInteger($arg_array['extraPoints'], 1) && strlen($arg_array['extraPoints']) > 4) {
                return array( 'code' => 400, 'message' => '额外赠送积分不能为空且是大于0的4位整数' );
            }
            if (!$commHandler->isInteger($arg_array['continuousDay'], 1) && strlen($arg_array['continuousDay']) > 4) {
                return array( 'code' => 400, 'message' => '连续签到天数必须是大于0的4位整数' );
            }
        }

        if (!is_numeric($arg_array['promotionID']) || $arg_array['promotionID'] < 0) {
            $arg_array['promotionID'] = 0;
        }

        try {

            $promotion_sign = new entity('promotion_sign_in');
            if ($arg_array['promotionID'] == 0) {
                $promotion_sign->promotionID = $commHandler->generate_seqno('seqno_promotion');
                $promotion_sign->creator = $arg_array['operator'];
            } else {
                $promotion_sign->promotionID = $arg_array['promotionID'];
                if (!$this->dbca->fetch($promotion_sign)) {
                    throw new Exception('签到活动没有找到', 404);
                }
            }
            $promotion_sign->promotionName = $arg_array['promotionName'];
            $promotion_sign->description = $arg_array['description'];
            $promotion_sign->startDate = $arg_array['startDate'];
            $promotion_sign->endDate = $arg_array['endDate'];
            $promotion_sign->points = $arg_array['points'];
            $promotion_sign->continuousDay = $arg_array['continuousDay'];
            $promotion_sign->extraPoints = $arg_array['extraPoints'];
            $this->dbca->save($promotion_sign);

            return array( 'code'=>200, 'message' => '保存成功' );

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 删除签到活动
     * @param $arg_array
     * @return array|null
     */
    public function deleteSignIn(&$arg_array){

        if (!isset($arg_array['pid'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        try{

            foreach($arg_array['pid'] as $val){
                $this->dbca->stmt_query('DELETE FROM promotion_sign_in WHERE promotionID = ?','i',$val);
            }

            return array('code'=>200,'message'=>'删除成功');

        }catch(Exception $e){
            error_log($e->getMessage());
            return null;
        }

    }

    /**
     * 查询签到活动奖项设置
     * @param $arg_array
     * @return array|null
     */
    public function searchSigneToAwardsList(&$arg_array){

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //签到活动ID
        if (isset($arg_array['promotionID']) && is_numeric($arg_array['promotionID'])) {
            $sql .= ' AND promotionID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['promotionID'];
        }

        //签到奖项ID
        if (isset($arg_array['awardsID']) && !empty($arg_array['awardsID'])) {
            $sql .= ' AND awardsID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['awardsID'];
        }

        //连续签到开始天数
        if (isset($arg_array['startDay']) && !empty($arg_array['startDay'])) {
            $sql .= ' AND startDay = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['startDay'];
        }

        //连续签到结束天数
        if (isset($arg_array['endDay']) && !empty($arg_array['endDay'])) {
            $sql .= ' AND endDay = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['endDay'];
        }

        //累计天数
        if (isset($arg_array['accumulativeDate']) && is_numeric($arg_array['accumulativeDate'])) {
            $sql .= ' AND accumulativeDate = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['accumulativeDate'];
        }

        //积分

        if (isset($arg_array['points']) && is_numeric($arg_array['points'])) {
            $sql .= ' AND points = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['points'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4) ;
        }

        try {

            if (isset($arg_array['rp'])) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM promotion_sign_in_awards  ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询备注信息
            $search_sql = 'SELECT * FROM promotion_sign_in_awards ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

            if (!$temp_item_array)
                return null;

            if ($temp_item_array) {
                foreach ($temp_item_array as &$item) {
                    $item_array[] = array(
                        'createTime' => $item->createTime,                //创建时间
                        'promotionID' => $item->promotionID,                //签到活动ID
                        'awardsID' => $item->awardsID,            //签到奖项ID
                        'startDay' => $item->startDay,            //连续签到开始天数
                        'endDay' => $item->endDay,            //连续签到结束天数
                        'accumulativeDate' => $item->accumulativeDate,            //累计天数
                        'points' => $item->points,            //积分
                        'gift' => $item->gift                   //赠品
                    );
                }
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    public function searchSignInLog( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //签到活动ID
        if (isset($arg_array['promotionID']) && is_numeric($arg_array['promotionID'])) {
            $sql .= ' AND promotionID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['promotionID'];
        }

        //签到活动ID
        if (isset($arg_array['pcustID']) && is_numeric($arg_array['pcustID'])) {
            $sql .= ' AND pcustID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['pcustID'];
        }

        //日期
        if (isset($arg_array['date']) && !empty($arg_array['date'])) {
            $sql .= ' AND signInDate = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['date'];
        }

        //范围日期
        if (isset($arg_array['startDate']) && !empty($arg_array['startDate']) && isset($arg_array['endDate']) && !empty($arg_array['endDate'])) {
            $sql .= ' AND signInDate BETWEEN ? AND ?';
            $params_type .= 'ss';
            $params_array[] = $arg_array['startDate'];
            $params_array[] = $arg_array['endDate'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4) ;
        }

        try {

            if (isset($arg_array['rp'])) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM promotion_sign_in_log  ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询备注信息
            $search_sql = 'SELECT * FROM promotion_sign_in_log ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

            if (!$temp_item_array)
                return null;

            if ($temp_item_array) {
                foreach ($temp_item_array as &$item) {

                    $item_array[] = array(
                        'promotionID' => $item->promotionID,
                        'pcustID' => $item->pcustID,
                        'signInDate' => $item->signInDate,
                        'createTime' => $item->createTime,
                        'points' => $item->points,
                        'remark' => $item->remark
                    );
                }
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 保存用户签到
     */
    function saveCheckIn( $pcustID, $promotionID, $eai ){

        if( !isset($pcustID, $promotionID) || !is_numeric($pcustID) || !is_numeric($promotionID) )
            return array( 'code' => 400 , 'message' => '参数错误' );

        $date = date(G_DEFAULT_DATE_FORMAT);

        try {

            //查询签到活动
            $temp_arg_array = array(
                'promotionID' => $promotionID,
                'useFlg' => 1
            );
            $check_in_array = $this->searchSigneToList( $temp_arg_array );
            if (!$check_in_array) {
                throw new Exception('签到活动信息没有找到', 404);
            }
            $check_in_array = $check_in_array[0];

            //检查当天是否已签到
            $arg_array = array(
                'promotionID' => $check_in_array['promotionID'],
                'pcustID' => $pcustID,
                'startDate' => $date,
                'endDate' => $date
            );
            $sign_in_log_array = $this->searchSignInLog( $arg_array );
            if ($sign_in_log_array) {
                throw new Exception('您今天已签到', 404);
            }

            $points = $check_in_array['points'];
            $extraPoints = 0;

            //如果签到活动有连续签到送额外积分，则记录最后一次签到，并计算连续天数，如果连续天数符合条件，则赠送额外积分
            if ($check_in_array['continuousDay'] > 0) {

                //检查并保存会员最后一次签到
                $sign_in_last_obj = new entity('promotion_sign_last');
                $sign_in_last_obj->promotionID = $check_in_array['promotionID'];
                $sign_in_last_obj->pcustID = $pcustID;
                if ($this->dbca->fetch($sign_in_last_obj)) {

                    //检查会员最后一次签到是否前一天
                    if ($sign_in_last_obj->lastDate == date("Y-m-d",strtotime("-1 day"))) {

                        $sign_in_last_obj->num += 1;

                        //加上当前签到如果等于连续签到天数，则赠送额外积分，同时，连续签到天数设为0
                        if ($sign_in_last_obj->num == $check_in_array['continuousDay']) {
                            $sign_in_last_obj->num = 0;
                            $extraPoints = $check_in_array['extraPoints'];
                        }

                    } else {

                        $sign_in_last_obj->num = 1;

                    }

                    $sign_in_last_obj->lastDate = $date;

                } else {

                    $sign_in_last_obj->creator = 'system_sign_in';
                    $sign_in_last_obj->lastDate = $date;
                    $sign_in_last_obj->num = 1;

                }

                $this->dbca->save($sign_in_last_obj);

            }


            //保存签到记录
            $sign_in_log_obj = new entity('promotion_sign_in_log');
            $sign_in_log_obj->creator = 'system_check_in';
            $sign_in_log_obj->promotionID = $check_in_array['promotionID'];
            $sign_in_log_obj->pcustID = $pcustID;
            $sign_in_log_obj->signInDate = $date;
            $sign_in_log_obj->points = $points + $extraPoints;
            if ($extraPoints > 0) {
                $sign_in_log_obj->remark = '+' . $points . '，额外赠送良票+' . $extraPoints;
            } else {
                $sign_in_log_obj->remark = '+' . $points;
            }
            $this->dbca->save($sign_in_log_obj);

            //调用CRM会员账户修改接口
            $arg_array = array(
                'pcustID' => $pcustID,
                'payTypeID' => G_PAYTYPE_POINTS,
                'amount' => $points + $extraPoints,
                'operator' => '系统',
                'remark' => '签到良票+' . $points,
                'externalTranCode' => '',
                'source' => ''
            );
            if ($extraPoints > 0) {
                $arg_array['remark'] = '签到良票+' . $points . ',额外赠送良票+' . $extraPoints;
            }
            $eai->memberRecharge( $arg_array, $this->dbca );

            return array( 'code' => 200 , 'message' => '签到成功', 'data' => array( 'points' => $points ) );

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    public function useSigned( $arg_array ) {

        if (!isset($arg_array['promotionID'], $arg_array['useFlg']) || !is_numeric($arg_array['promotionID']) || !in_array($arg_array['useFlg'], array(0, 1))) {
            return array( 'code' => 200, 'message' => '参数错误' );
        }

        try {

            $sign_in_obj = new entity('promotion_sign_in');
            $sign_in_obj->promotionID = $arg_array['promotionID'];
            if (!$this->dbca->fetch($sign_in_obj)) {
                throw new Exception('签到活动不存在', 404);
            }
            if ($arg_array['useFlg'] == 1 && $sign_in_obj->useFlg == 1) {
                throw new Exception('签到活动已启用', 404);
            }
            if ($arg_array['useFlg'] == 0 && $sign_in_obj->useFlg == 0) {
                throw new Exception('签到活动已禁用', 404);
            }
            $sign_in_obj->useFlg = $arg_array['useFlg'];
            $this->dbca->save($sign_in_obj);

            if ($arg_array['useFlg']) {
                return array( 'code' => 200 , 'message' => '启用成功' );
            } else {
                return array( 'code' => 200 , 'message' => '禁用成功' );
            }

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

}